/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Servlet;

import java.io.*;
import java.net.*;

import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 *
 * @author Mat
 */
public class fileOptions extends HttpServlet {

    private Element racine;
    private PrintWriter out;
    private String optionFile = "";
    ArrayList<String> listOptions;
    ArrayList<Integer> tagCloudOptions;

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        if (request.getParameter("mod").equals("list")) {
            listMethod(request, response);
        } else if (request.getParameter("mod").equals("tagcloud")) {
            tagCloudMethod(request, response);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     */
    public String getServletInfo() {
        return "Short description";
    }
    // </editor-fold>
    private Document openXMLDocument(String fileToOpen) throws SAXException, IOException, ParserConfigurationException {
        //On crée un nouveau document JDOM avec en argument le fichier XML
        //Le parsing est terminé ;)
        DocumentBuilderFactory fabrique = DocumentBuilderFactory.newInstance();

        // création d'un constructeur de documents
        DocumentBuilder constructeur = fabrique.newDocumentBuilder();

        // lecture du contenu d'un fichier XML avec DOM
        String nameFile = "xml/";
        nameFile += fileToOpen;
        File xml = new File(nameFile);
        return constructeur.parse(xml);
    }

    private void listMethod(HttpServletRequest request, HttpServletResponse response) {
        Document document;
        listOptions = new ArrayList<String>();

        try {
            out = response.getWriter();
            document = openXMLDocument(request.getParameter("file"));
            racine = document.getDocumentElement();
            if (racine.hasChildNodes()) {
                if (!listOptions.contains(racine.getNodeName().toLowerCase())) {
                    listOptions.add(racine.getNodeName().toLowerCase());
                }
                listSearch(racine);
            }
            listDoc();
            response.sendRedirect("Liste.html");
        } catch (SAXException ex) {
            Logger.getLogger(fileOptions.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(fileOptions.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(fileOptions.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            out.close();
        }
    }

    private void listSearch(Element racineTemp) {
        Node temp;
        NodeList tousLesFils = racineTemp.getChildNodes();
        String option = "";
        for (int i = 0; i < tousLesFils.getLength(); i++) {
            temp = tousLesFils.item(i);
            if (!temp.getNodeName().contains("#")) {
                option = temp.getNodeName().toLowerCase();
                if (!listOptions.contains(option)) {
                    listOptions.add(option);
                }
                if (temp.getChildNodes().getLength() > 1) {
                    listSearch((Element) temp);
                } else {
                    option = temp.getTextContent().toLowerCase();
                    if (!listOptions.contains(option)) {
                        listOptions.add(option);
                    }
                }
            }
        }
    }

    private void creerDoc(String namefile) throws IOException {
        PrintWriter option = null;
        try {
            option = new PrintWriter(new FileWriter("webapps/ProjetAutoCompletion/" + namefile));
            option.write(optionFile);
            optionFile += "";
        } catch (FileNotFoundException ex) {
            Logger.getLogger(fileOptions.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            option.close();
        }
    }

    private void tagCloudMethod(HttpServletRequest request, HttpServletResponse response) {
        try {
            listOptions = new ArrayList<String>();
            tagCloudOptions = new ArrayList<Integer>();
            Document document;
            out = response.getWriter();
            document = openXMLDocument(request.getParameter("file"));
            racine = document.getDocumentElement();
            if (racine.hasChildNodes()) {
                if (!listOptions.contains(racine.getNodeName().toLowerCase())) {
                    listOptions.add(racine.getNodeName().toLowerCase());
                    tagCloudOptions.add(1);
                }
                tagCloudSearch(racine);
            }
            tagCloudDoc();
            response.sendRedirect("tagCloud.html");
        } catch (SAXException ex) {
            Logger.getLogger(fileOptions.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(fileOptions.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(fileOptions.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void tagCloudSearch(Element racineTemp) {
        Node temp;
        NodeList tousLesFils = racineTemp.getChildNodes();
        String option = "";
        for (int i = 0; i < tousLesFils.getLength(); i++) {
            temp = tousLesFils.item(i);
            if (!temp.getNodeName().contains("#")) {
                option = temp.getNodeName().toLowerCase();
                if (listOptions.contains(option)) {
                    tagCloudOptions.set(listOptions.indexOf(option), (tagCloudOptions.get(listOptions.indexOf(option)) + 1));
                } else {
                    listOptions.add(option);
                    tagCloudOptions.add(1);
                }
                if (temp.getChildNodes().getLength() > 1) {
                    tagCloudSearch((Element) temp);
                } else {
                    option = temp.getTextContent().toLowerCase();
                    if (listOptions.contains(option)) {
                        tagCloudOptions.set(listOptions.indexOf(option), (tagCloudOptions.get(listOptions.indexOf(option)) + 1));
                    } else {
                        listOptions.add(option);
                        tagCloudOptions.add(1);
                    }
                }
            }
        }
    }

    private void listDoc() {
        try {
            optionFile = "collection = [";
            for (String optionString : listOptions) {
                if (listOptions.indexOf(optionString) == 0) {
                    optionFile += "'" + optionString + "'";
                } else {
                    optionFile += "," + "'" + optionString + "'";
                }
            }
            optionFile += "];";
            creerDoc("options.js");
        } catch (IOException ex) {
            Logger.getLogger(fileOptions.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void tagCloudDoc() {
        try {
            optionFile = "<options>";
            for (String optionString : listOptions) {
                optionFile += "<option>" + optionString;
                optionFile += ":" + tagCloudOptions.get(listOptions.indexOf(optionString));
                optionFile += "</option>";
            }
            optionFile += "</options>";
            creerDoc("options.xml");
        } catch (IOException ex) {
            Logger.getLogger(fileOptions.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}










